import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',  
    redirect: '/login',  
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    redirect:'/welcome',
    component: () => import("../components/Home.vue"),
    children:[{
      path: '/welcome',
      name: 'Welcome',
      component: () => import("../components/Welcome.vue"),
      },
      {
        path: '/users',
        name: 'User',
        component: () => import("../components/user/user.vue"),
      },
      {
        path: '/reports',
        name: 'Reports',
        component: () => import("../components/report/reports.vue"),
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 添加全局导航守卫
router.beforeEach((to,from,next) =>{
  // 如果要跳转的页面是登录页，则可以跳转
  if(to.name=='Login') return next();
  // 如果要跳转的页面不是登录页，需要获取token，
  const token = window.sessionStorage.getItem('token')
   // 如果没有token，或者验证不成功，则跳转到登录页
  if(!token) return next({ name: 'Login' })
  // 如果有token且要和服务器进行验证，验证成功之后，则可以跳转其他页面
  next()
})
export default router
